package com.ithaipeng.redanttakeaway.exception;

import com.ithaipeng.redanttakeaway.tools.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 这是一个全局异常
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler  {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exception(SQLIntegrityConstraintViolationException exception){
        log.info(exception.getMessage());
        if(exception.getMessage().contains("Duplicate entry")) {
            String[] msgs = exception.getMessage().split(" ");
            String message = msgs[2] + "已经存在";
            return Result.error(message);
        }else {
            return Result.error("未知错误!");
        }
    }
    @ExceptionHandler(CustomException.class)
    public Result<String> exception(CustomException customException){
        return Result.error(customException.getMessage());
    }
}
